package compraventa.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import compraventa.modelo.Categoria;
import compraventa.modelo.Persona;
import compraventa.negocio.GestionCategoria;

/**
 * Servlet implementation class CategoriaInsertarServlet
 */
@WebServlet("/CategoriaInsertarServlet")
public class CategoriaInsertarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public CategoriaInsertarServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		GestionCategoria negocio = new GestionCategoria();
		Collection<Categoria> lista;
		try {
			lista = negocio.listar(0);
			request.setAttribute("lista", lista);
			RequestDispatcher rd = request.getRequestDispatcher("scv_registro_categoria.jsp");
			rd.forward(request, response);
		} catch (Exception e) {
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nom = request.getParameter("nombre");
		String des = request.getParameter("descripcion");
		String sidcat = request.getParameter("optCategoria");
		int cat = 0;
		int per = 0;
		GestionCategoria negocio = new GestionCategoria();
		HttpSession session = request.getSession();
		try {
			Persona usuario_actual = (Persona)session.getAttribute("USUARIO");
			cat = Integer.parseInt(sidcat);
			per = usuario_actual.getIdPersona();
			negocio.insertar(nom, des, cat, per);
			response.sendRedirect(request.getContextPath()	+ "/scv_principal.jsp");
		} catch (Exception e) {
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
	}

}
